<template>
    <div v-if="false" class="w-full border border-slate-200 dark:border-slate-600 bg-slate-100 dark:bg-slate-800 p-2.5 flex items-center justify-end flex-row flex-nowrap justify-between">
        <div @click="clearable" class="rounded border dark:border-gray-500 py-1 px-2 light:border-gray-200 border-solid dark:bg-slate-500 cursor-pointer light:bg-slate-100 text-sm">清空内容</div>
        <div @click="clearable" class="rounded border dark:border-gray-500 py-1 px-2 light:border-gray-200 border-solid dark:bg-slate-500 cursor-pointer light:bg-slate-100 text-sm">复制</div>
    </div>
    <div ref="editorView" :class="['diff-container border bg-slate-800 border-slate-600 shadow-lg bg-white overflow-hidden rounded-md']"></div>
</template>

<script lang="ts" setup>
import { keymap ,lineNumbers,highlightActiveLine,drawSelection,highlightActiveLineGutter,highlightSpecialChars} from '@codemirror/view';
import { autocompletion } from '@codemirror/autocomplete';
import { EditorView,basicSetup} from "codemirror"
import {MergeView} from "@codemirror/merge";
import {search} from "@codemirror/search"
import { standardKeymap, insertTab,defaultKeymap} from '@codemirror/commands';
import { oneDarkTheme, oneDarkHighlightStyle,color } from '@codemirror/theme-one-dark';
const appstore = useAppStore()
const editorView = ref();
const theme = ref()
const emit = defineEmits(['update:left','update:right','update:Value'])
const doc = reactive({
    left: 'function add(a, b) {\n    return a + b;\n}',
    right: 'function add(a, b) {\n    return a + b;\n}',
    highlightDifferences: true,
    collapseIdentical: true
});

useHead({
  title: '代码比对',
  meta: [
    { hid: "keywords", name: "keywords", content: "代码比对、代码编辑、在线代码比对、diff、代码对比" },
    { hid: "description", name: "description", content: "在线代码对比/合并工具方便程序员查找出2段代码间的差异，并能进行合并。" },
  ]
})


function getDoc(){
    return {
        left: editorView.value?.a?.state.doc.toString(),
        right: editorView.value?.b?.state.doc.toString()
    }
}

function getConfig(doc:any = ''){
    return {
        doc,
        oneDarkTheme,
        oneDarkHighlightStyle,
        lineWrapping: true,
        autoRefresh:true,
        indentUnit: 4,
        highlightChanges: true,
        matchBrackets: true,
        indentWithTabs: true,
        styleActiveLine: true,
        highlightDifferences:true,
        collapseIdentical:true,
        // mode:'text/html',
        foldGutter: true,
        extensions: [
            basicSetup,
            search({
                top:false
            }),
            // javascript(),
            drawSelection(),
            lineNumbers(),
            highlightActiveLine(),
            highlightActiveLineGutter(),
            highlightSpecialChars(),
            // highlightWhitespace(),
            
            keymap.of([...standardKeymap,...defaultKeymap,{ key: 'Tab', run: insertTab }]),
            autocompletion({ activateOnTyping: true }),
            EditorView.updateListener.of((v) => {
                if (v.docChanged) {
                    const target = (v.view as any)?.editorAttrs?.class.includes('cm-merge-a')?'left':'right';
                    if(target ==='left'){
                        emit('update:left', {content:v.state.doc.toString(),v});
                        // doc.left = v.state.doc.toString();
                    }else{
                        // doc.right = v.state.doc.toString()
                        emit('update:right', {content:v.state.doc.toString(),v});
                    }
                }
            }),
        ]
    }
}

const createEditor = (editorContainer:HTMLElement, leftdoc:any,rightdoc:any) => {
        editorView.value = new MergeView({
            a:getConfig(leftdoc),
            b:getConfig(rightdoc),
            parent:editorContainer,
        })
};

onMounted(() => {
    createEditor(editorView.value, doc.left, doc.right);
    theme.value = appstore.theme;
});

function clearable() {
    if(editorView.value){
        doc.left = '';
        doc.right = '';
        editorView.value?.a.dispatch({changes:{from:0,to:editorView.value.a.state.doc.length,insert:''}});
        editorView.value?.b.dispatch({changes:{from:0,to:editorView.value.b.state.doc.length,insert:''}});
    };
}

/* 监听store的变化 */
appstore.$subscribe((mutation, state)=>{
    theme.value = state.theme;
})
</script>
<style lang="scss" scoped>
.diff-container{
    height: calc(100vh - var(--header-menu-height) - var(--footer-copyright-height));
    color: var(--text-custom-color);
    :deep(.cm-mergeView) {
        height: 100%;
        overflow-y: auto;
        @include scrollBar();
        .cm-mergeViewEditors{
            min-height: 100%;
            .cm-mergeViewEditor{
                min-height: 100%;
                border-right: 1px solid rgba($color: #fff, $alpha: 0.2); 
                &:last-child{
                    border-right: none;
                }
            }
        }
    }
}
.diff-dark{
    color: rgba($color: #fff, $alpha: 0.8);
    background-color: rgba($color: #000000, $alpha: 0.8);
}
.diff-light{
    color: rgba($color: #000, $alpha: 0.8);
    background-color: #fff;
}
</style>